package com.jy.rhin.facade.schedule;

import com.jy.framework.base.entity.Page;
import com.jy.rhin.application.basic.event.PublishMessageEvent;
import com.jy.rhin.config.MessageCompensationProperties;
import com.jy.rhin.infra.repo.notfication.publish.query.PublishMessageQueryHandler;
import com.jy.rhin.sdk.dto.notification.req.FailPublishMessageReqDto;
import com.jy.rhin.sdk.dto.notification.resp.PublishMessageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author dhl
 * @date 2022/7/6
 * @Description
 */
@Slf4j
@Component
public class MessageSchedule {

    @Resource
    private PublishMessageQueryHandler publishMessageQueryHandler;
    @Resource
    private MessageCompensationProperties messageCompensationProperties;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 推送失败消息补偿定时器
     */
    @Scheduled(cron = "${message.compensation.cronStr}")
    public void sendFailedMessageCompensation() {
        log.debug("-----查询推送失败的消息列表定时器：start ------------------------");
        int i = 1;
        int size = 10;
        while (messageCompensation(i++, size)) {
            log.info("事件已通知 第{}批推送失败的消息列表", i);
        }
        log.debug("-----事件已通知 查询推送失败的消息列表定时器：end ------------------------");
    }


    /**
     * 根据配置获取推送失败的消息列表并事件通知
     */
    private boolean messageCompensation(int current, int size){
        FailPublishMessageReqDto req = new FailPublishMessageReqDto();
        req.setPublishCount(messageCompensationProperties.getPublishCount());
        req.setQueryDay(messageCompensationProperties.getQueryDay());
        req.setCurrent(current);
        req.setSize(size);

        Page<PublishMessageDto> page =publishMessageQueryHandler.querySendFailPublishMessagePage(req);
        List<PublishMessageDto> publishMessageList = page.getRecords();
        if(CollectionUtils.isEmpty(publishMessageList)){
            log.debug("----------没有推送失败的消息列表，查询推送失败的消息列表定时器：end ---------------");
            return false;
        }
        applicationEventPublisher.publishEvent(new PublishMessageEvent(publishMessageList));
        return publishMessageList.size() == size;
    }
}
